import { addResizeListener, removeResizeListener } from 'utils/resize-event'

const getHeight = (el) => el.offsetHeight

const toNumber = (n) => parseInt(n, 10) || 0

// 获取元素某个方向的padding值，这里用 IIFE 写是为了避免每次调用都要判断是不是ie
const getPadding = (function () {
  const isIE = !!document.body.currentStyle
  if (isIE) {
    return (el, direction) => toNumber(el.currentStyle[direction])
  } else {
    return (el, direction) => toNumber(getComputedStyle(el, false)[direction])
  }
}())

const getParentHeight = (parent) => {
  const pt = getPadding(parent, 'paddingTop');
  const pb = getPadding(parent, 'paddingBottom');
  return parent.clientHeight - pt - pb;
};

export default {
  data() {
    return {
      tableHeight: 100,
      resizeElement: null,
    }
  },
  methods: {
    $calcTableHeight() {
      const tableExtra = this.$el.querySelector('.g-table-extra')
      const tableHeader = this.$el.querySelector('.g-table-header')
      const top = this.$el.querySelector('.g-table-top')
      const bottom = this.$el.querySelector('.g-table-bottom')
      let tableEl = this.$el
      const tableExtraData = parseInt(tableEl.getAttribute('data-table-extra') || 0, 10)
      if (this.tableEl) {
        tableEl = this.$el.querySelector(this.tableEl)
      }
      const currentPaddingTop = getPadding(tableEl, 'paddingTop') || 0

      if (tableEl.parentNode) {
        const parent = tableEl.parentNode.parentNode
        const topHeight = top ? getHeight(top) : 0
        const headerHeight = tableHeader ? getHeight(tableHeader) + 16 : 0
        const tableExtraHeight = tableExtra ? getHeight(tableExtra) : 0
        const bottomHeight = bottom ? getHeight(bottom) : 0
        if (parent) {
          this.tableHeight = getParentHeight(parent) - currentPaddingTop - topHeight - bottomHeight - headerHeight - tableExtraHeight - tableExtraData
        }
      }
    }
  },
  mounted() {
    const prefix = this.$store.state.appPrefix
    const rightEle = this.$el.querySelector(`.${prefix}-layout-drag__right`)
    this.resizeElement = rightEle || this.$el
    addResizeListener(this.resizeElement, this.$calcTableHeight)
  },
  beforeDestroy() {
    if (this.resizeElement && this.$calcTableHeight) {
      removeResizeListener(this.resizeElement, this.$calcTableHeight)
    }
  },
};
